<template>
    <div class="app-container">
        <el-form
            :model="queryParams"
            ref="queryRef"
            :inline="true"
            v-show="showSearch"
        >
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="姓名" prop="name">
                        <el-input
                            v-model="queryParams.name"
                            placeholder="姓名"
                            clearable
                            @keyup.enter.native="handleQuery"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="手机号" prop="phone">
                        <el-input
                            v-model="queryParams.phone"
                            placeholder="手机号"
                            clearable
                            @keyup.enter.native="handleQuery"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="状态" prop="status">
                        <el-select v-model="statusModel" placeholder="请选择状态" style="width: 100%">
                            <el-option
                                v-for="item in statusOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-button type="primary" @click="handleQuery">搜索</el-button>
                    <el-button @click="resetQuery">重置</el-button>
                </el-col>
            </el-row>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="Plus"
                    @click="handleAdd"
                    v-hasPermi="['system:employee:add']"
                    >新增</el-button
                >
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="Edit"
                    :disabled="single"
                    @click="handleUpdate"
                    v-hasPermi="['system:employee:edit']"
                    >修改</el-button
                >
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="Delete"
                    :disabled="multiple"
                    @click="handleDelete"
                    v-hasPermi="['system:employee:remove']"
                    >删除</el-button
                >
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="warning"
                    plain
                    icon="Download"
                    @click="handleExport"
                    v-hasPermi="['system:employee:export']"
                    >导出</el-button
                >
            </el-col>
            <right-toolbar
                v-model:showSearch="showSearch"
                @queryTable="getList"
            ></right-toolbar>
        </el-row>

        <el-table
            v-loading="loading"
            :data="employeeList"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="name" label="姓名" align="center" />
            <el-table-column prop="idCard" label="身份证" align="center" />
            <el-table-column prop="phone" label="手机号" align="center" />
            <el-table-column prop="bankCard" label="银行卡号" align="center" />
            <el-table-column prop="status" label="状态" align="center" :formatter="statusFormatter" />
            <!-- <el-table-column prop="deptName" label="部门" align="center" /> -->
            <el-table-column prop="hireDate" label="入职时间" align="center" />
            <el-table-column prop="resignationDate" label="离职时间" align="center" />
            <el-table-column prop="updateTime" label="更新时间" align="center" />
            
           
            <el-table-column
                label="操作"
                width="180"
                align="center"
                class-name="small-padding fixed-width"
            >
                <template #default="scope">
                    <el-button
                        link
                        type="primary"
                        icon="Edit"
                        @click="handleUpdate(scope.row)"
                        v-hasPermi="['system:employee:edit']"
                        >修改</el-button
                    >
                    <el-button
                        link
                        type="primary"
                        icon="Delete"
                        @click="handleDelete(scope.row)"
                        v-hasPermi="['system:employee:remove']"
                        >删除</el-button
                    >
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total > 0"
            :total="total"
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改员工对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
            <el-form
                ref="employeeRef"
                :model="form"
                :rules="rules"
                label-width="80px"
            >
                <el-form-item label="员工姓名" prop="name">
                    <el-input
                        v-model="form.name"
                        placeholder="请输入员工姓名"
                    />
                </el-form-item>
                <el-form-item label="身份证" prop="idCard">
                    <el-input
                        v-model="form.idCard"
                        placeholder="请输入身份证"
                    />
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                    <el-input
                        v-model="form.phone"
                        placeholder="请输入手机号码"
                        maxlength="11"
                    />
                </el-form-item>
                <el-form-item label="银行卡号" prop="bankCard">
                    <el-input
                        v-model="form.bankCard"
                        placeholder="请输入银行卡号"
                        maxlength="30"
                    />
                </el-form-item>
                <el-form-item label="入职时间" prop="hireDate">
                    <el-date-picker
                        v-model="form.hireDate"
                        type="date"
                        placeholder="请选择入职时间"
                        style="width: 100%;"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                    />
                </el-form-item>
                <!-- <el-form-item label="邮箱" prop="email">
                    <el-input
                        v-model="form.email"
                        placeholder="请输入邮箱"
                        maxlength="50"
                    />
                </el-form-item> -->
                <!-- <el-form-item label="部门" prop="deptId">
                    <el-tree-select
                        v-model="form.deptId"
                        :data="deptOptions"
                        :props="{ value: 'id', label: 'label', children: 'children' }"
                        value-key="id"
                        placeholder="请选择所属部门"
                    />
                </el-form-item> -->
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="form.status">
                        <el-radio :label="'0'">在职</el-radio>
                    </el-radio-group>
                </el-form-item>
                <!-- <el-form-item label="备注" prop="remark">
                    <el-input
                        v-model="form.remark"
                        type="textarea"
                        placeholder="请输入内容"
                    />
                </el-form-item> -->
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Employee">
// 新增员工vue - 前端name去重 - 校验手机号规则 -身份证规则
import {
    listEmployee,
    addEmployee,
    delEmployee,
    getEmployee,
    updateEmployee,
    exportEmployee,
    checkEmployeeNameUnique
} from '@/api/system/employee'
import { listDept } from '@/api/system/dept'
import { watch, computed } from 'vue'

const { proxy } = getCurrentInstance()
const { sys_normal_disable, sys_user_sex } = proxy.useDict('sys_normal_disable', 'sys_user_sex')

const employeeList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const deptOptions = ref([])

const data = reactive({
    form: {
        employeeId: undefined,
        name: undefined,
        idCard: undefined,
        phone: undefined,
        bankCard: undefined,
        hireDate: undefined,
        email: undefined,
        deptId: undefined,
        status: '0', // 只允许在职
        remark: undefined
    },
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: '',
        phone: '',
        status: '0'
    },
    rules: {
        name: [
            { required: true, message: '员工姓名不能为空', trigger: 'blur' },
            {
                async validator(rule, value, callback) {
                    if (!value) return callback();
                    const res = await checkEmployeeNameUnique(value);
                    if (res.data && res.data.unique === false) {
                        callback(new Error('员工姓名已存在'));
                    } else {
                        callback();
                    }
                },
                trigger: 'blur'
            }
        ],
        phone: [
            {
                pattern: /^1[3-9]\d{9}$/,
                message: '请输入正确的11位手机号',
                trigger: 'blur'
            }
        ],
        idCard: [
            {
                pattern: /^\d{17}[\dXx]$/,
                message: '请输入正确的18位身份证号',
                trigger: 'blur'
            }
        ],
        bankCard: [
            {
                pattern: /^\d{16,19}$/,
                message: '请输入16-19位银行卡号',
                trigger: 'blur'
            }
        ]
    }
})

const { queryParams, form, rules } = toRefs(data)

const statusOptions = [
    { label: '在职', value: '0' },
    { label: '离职', value: '1' },
    { label: '停用', value: '2' }
]

const statusModel = computed({
    get: () => String(queryParams.status ?? ''),
    set: val => { queryParams.status = String(val) }
})

/** 功能一：查询员工列表 */
function getList() {
    loading.value = true
    listEmployee(queryParams.value).then((response) => {
        employeeList.value = response.rows
        total.value = response.total
        loading.value = false
    })
}

/** 查询部门下拉树结构 */
function getDeptTree() {
    listDept().then(response => {
        deptOptions.value = response.data
    })
}

/** 取消按钮 */
function cancel() {
    open.value = false
    reset()
}

/** 表单重置 */
function reset() {
    form.value = {
        id: undefined,
        name: undefined,
        idCard: undefined,
        phone: undefined,
        bankCard: undefined,
        hireDate: undefined,
        email: undefined,
        deptId: undefined,
        status: '0', // 只允许在职
        remark: undefined
    }
    proxy.resetForm('employeeRef')
}

/** 搜索按钮操作 */
function handleQuery() {
    if (typeof queryParams.status !== 'string') {
        queryParams.status = queryParams.status !== undefined && queryParams.status !== null ? String(queryParams.status) : ''
    }
    queryParams.value.pageNum = 1
    getList()
}

/** 重置按钮操作 */
function resetQuery() {
    queryParams.name = ''
    queryParams.phone = ''
    queryParams.status = ''
    proxy.resetForm('queryRef')
    handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.employeeId)
    single.value = selection.length != 1
    multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
    reset()
    getDeptTree()
    open.value = true
    title.value = '添加员工'
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset()
    getDeptTree()
    const employeeId = row.employeeId || ids.value
    getEmployee(employeeId).then((response) => {
        form.value = response.data
        open.value = true
        title.value = '修改员工'
    })
}

/** 提交按钮 -新增员工 */
function submitForm() {
    proxy.$refs['employeeRef'].validate((valid) => {
        if (valid) {
            if (form.value.employeeId != undefined) {
                updateEmployee(form.value).then((response) => {
                    proxy.$modal.msgSuccess('修改成功')
                    open.value = false
                    getList()
                })
            } else {
                addEmployee(form.value).then((response) => {
                    proxy.$modal.msgSuccess('新增成功')
                    open.value = false
                    getList()
                })
            }
        }
    })
}

/** 删除按钮操作 */
function handleDelete(row) {
    const employeeIds = row.employeeId || ids.value
    proxy.$modal
        .confirm('是否确认删除员工编号为"' + employeeIds + '"的数据项？')
        .then(function () {
            return delEmployee(employeeIds)
        })
        .then(() => {
            getList()
            proxy.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
    proxy.download(
        'system/employee/export',
        {
            ...queryParams.value
        },
        `employee_${new Date().getTime()}.xlsx`
    )
}

function statusFormatter(row) {
    switch (row.status) {
        case '0':
        case 0:
            return '在职'
        case '1':
        case 1:
            return '离职'
        case '2':
        case 2:
            return '停用'
        default:
            return row.status
    }
}

watch(() => queryParams.status, (val) => {
    console.log('当前状态值:', val, typeof val)
})

getDeptTree()
getList()
</script> 